package com.ch.web.redis;

import com.ch.web.entity.user.XyUserEntity;
import com.ch.web.service.XyTokenService;
import com.ch.web.utils.RedisUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 后续功能成熟时 采取使用redis 保存数据
 */
@Component
public class UserMapCache {
    @Autowired
    XyTokenService xyTokenService;
    /**
     * 缓存token和用户实体的map集合
     */
    @Resource
    RedisUtil redisUtil;

    public void setUserToken(String token, Object object, Date expireTime) {
        redisUtil.set(token, object, expireTime.getTime());
    }

    public boolean isHaveToken(String token) {
        return ObjectUtils.isNotEmpty(redisUtil.get(token));
    }

    public boolean isExpire(String token) {
        long expire = redisUtil.getExpire(token);
        return (expire - new Date().getTime() )< 0;
    }

    public Long getUserIdByToken(HttpServletRequest request) {
        return xyTokenService.getUserIdByToken(request.getHeader("token"));
    }

    public XyUserEntity getUserEntityBYToken(HttpServletRequest request) {
        return ((XyUserEntity) redisUtil.get(request.getHeader("token")));
    }
}
